package com.daocao.hua.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.daocao.hua.R;
import com.daocao.hua.api.callback.PaySelectContract;
import com.daocao.hua.api.requestInfo.PaySelectRequest;
import com.daocao.hua.constant.Const;
import com.daocao.hua.event.AlipayUserEvent;
import com.daocao.hua.event.OnHomeEventMsg;
import com.daocao.hua.model.BeeCloudModel;
import com.daocao.hua.model.ConfirmDilaogModel;
import com.daocao.hua.model.DealBeforeV3Model;
import com.daocao.hua.model.GoPayModel;
import com.daocao.hua.model.PayOrderModel;
import com.daocao.hua.model.PayWayModel;
import com.daocao.hua.model.RepayModel;
import com.daocao.hua.model.RepayStatusDialogModel;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.util.ScacheUtil;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.Dialog;
import com.daocao.hua.view.MyProgressView;
import com.daocao.hua.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/6/10.
 */

public class V3RepayMoneyActivity extends BaseActivity implements PaySelectContract.View {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.progress_normal)
    MyProgressView progressNormal;
    @BindView(R.id.progress_yuqi)
    SuperButton progressYuqi;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(R.id.txt_tips)
    TextView txtTips;
    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.txt_borrow_date)
    TextView txtBorrowDate;
    @BindView(R.id.txt_repay_date)
    TextView txtRepayDate;
    @BindView(R.id.txt_yuqi_fee)
    TextView txtYuqiFee;
    @BindView(R.id.cb_all)
    ImageView cbAll;
    @BindView(R.id.btn_xuqi_question)
    ImageView btnXuqiQuestion;
    @BindView(R.id.btn_xuqi)
    TextView btnXuqi;
    @BindView(R.id.img_xuqi)
    ImageView imgXuqi;
    @BindView(R.id.cb_xuqi)
    ImageView cbXuqi;
    @BindView(R.id.txt_alipay)
    TextView txtAlipay;
    @BindView(R.id.btn_alipay_add)
    LinearLayout btnAlipayAdd;
    @BindView(R.id.txt_money_all)
    TextView txtMoneyAll;
    @BindView(R.id.btn_pay_money)
    SuperButton btnPayMoney;
    @BindView(R.id.layout_top_color)
    SuperButton layoutTopColor;
    @BindView(R.id.txt_need_pay)
    TextView txtNeedPay;
    @BindView(R.id.txt_tips_bottom)
    TextView txtTipsBottom;
    @BindView(R.id.layout_top_color_sec)
    SuperButton layoutTopColorSec;
    @BindView(R.id.txt_benxi)
    TextView txtBenxi;
    @BindView(R.id.layout_xujie)
    LinearLayout layoutXujie;
    private Unbinder unbinder;
    private PaySelectRequest api;
    //    private float balance;
//    private int dikou_num;
//    private int totalMoney;
//    private String overdue;
//    private String mMoney;
//    private String dealId;
    private String payment_id;
    private String selectWays = ALI_APP;
    private static final String ALI_APP = "ALI_APP";
    private static final String ACTION_REPAY = "REPAY";
    private static final String ACTION_RENEWAL = "RENEWAL";

    private String ACTION = "REPAY";

    private ArrayList<PayWayModel.DataBean> payWayList;
    private boolean isGotoPay = false;
    private WebView mWebView;
    private String notice_sn;
    private ArrayList<String> explainList;
    private boolean isYuqi = false;
    private String trueMoney;
    private RepayModel.Data totalData;
    private String xuqiTotal;

    //还款
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repay_money_v3);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        mWebView = new WebView(getApplicationContext());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient());
        api = PaySelectRequest.create();
        api.attachView(this);
        api.getPayWay();

//        Intent dataIntent = getIntent();
//        dealId = dataIntent.getStringExtra("deal_id");
//        mMoney = dataIntent.getStringExtra("money");
//        overdue = dataIntent.getStringExtra("overdue");
//        balance = dataIntent.getFloatExtra("balance", 0f);
//        dikou_num = (int) balance;
//        totalMoney = dataIntent.getIntExtra("total_money", 0);
//        txtPayMoney.setText(new DecimalFormat("0.00").format(Float.parseFloat(mMoney)));
//        txtTotal.setText(totalMoney + "");
        if (!TextUtils.isEmpty(PreferenceUtils.getString(this, "u_alipay", ""))) {
            txtAlipay.setText(PreferenceUtils.getString(this, "u_alipay", ""));
        }
        api.getRepayData();
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.onPause();
            mWebView.destroy();
            mWebView = null;
        }
        api.detachView();
        api = null;
        ScacheUtil.clearTextLineCache();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
        unbinder = null;
        super.onDestroy();


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAlipayUser(AlipayUserEvent msg) {
        txtAlipay.setText(msg.user);
    }

    @OnClick({R.id.txt_right, R.id.btn_back, R.id.cb_all, R.id.btn_xuqi_question, R.id.btn_xuqi, R.id.cb_xuqi, R.id.btn_alipay_add, R.id.btn_pay_money})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_right:
                Util.startActivity(this, V3MyBorrowRecordActivity.class);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.cb_all:
                if (isYuqi) {
                    cbAll.setImageResource(R.mipmap.img_pay_check_red);

                } else {
                    cbAll.setImageResource(R.mipmap.img_pay_cb_open);
                }

                ACTION = ACTION_REPAY;
                cbXuqi.setImageResource(R.mipmap.img_pay_uncheck_repay);
                if (totalData != null) {
//                    txtNeedPay.setText(totalData.month_need_all_repay_money + "元");
//                    txtMoneyAll.setText(totalData.month_need_all_repay_money + "");
                    setMoneyData(false);
                }
                break;
            case R.id.btn_xuqi_question:
                Dialog.showDefaultV3Dialog(this, "续期还款", "续期还款是本平台对信用良好用户推出的快速续期的还款方式，续期成功将自动延长一个借款周期，请保持良好信用记录。",
                        "", "我知道了", new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {

                            }

                            @Override
                            public void cancel() {

                            }
                        });
                break;
            case R.id.btn_xuqi:
                Dialog.showDefaultV3Dialog(this, "续期还款", "续期还款是本平台对信用良好用户推出的快速续期的还款方式，续期成功将自动延长一个借款周期，请保持良好信用记录。",
                        "取消", "联系客服", new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {
                                Util.startActivity(V3RepayMoneyActivity.this, WechatChatActivity.class);
                            }

                            @Override
                            public void cancel() {

                            }
                        });
                break;
            case R.id.cb_xuqi:
                if (isYuqi) {
                    cbXuqi.setImageResource(R.mipmap.img_pay_check_red);

                } else {
                    cbXuqi.setImageResource(R.mipmap.img_pay_cb_open);
                }
                ACTION = ACTION_RENEWAL;
                cbAll.setImageResource(R.mipmap.img_pay_uncheck_repay);
                txtBenxi.setText("(续期+逾期费用)");
                if (totalData != null) {
//                    txtNeedPay.setText(totalData.renewal_money + "元");
//                    txtMoneyAll.setText(totalData.renewal_money + "");
                    setMoneyData(true);
                }

                break;
            case R.id.btn_alipay_add:
                Intent intent = new Intent(this, V3AlipayAddActivity.class);
                intent.putExtra("alipay", UI.toString(txtAlipay));
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_pay_money:
                if (TextUtils.isEmpty(payment_id)) {
                    api.getPayWay();
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(txtAlipay))) {
                    ToastUtil.makeText(this, "请选择支付宝账号").show();
                    return;
                }
                if (totalData == null) {
                    api.getRepayData();
                    return;
                }

                if (ACTION.equals(ACTION_RENEWAL)) {
                    api.getDealBefore();
                } else if (ACTION.equals(ACTION_REPAY)) {
                    Dialog.showAlipayAddTips(this, "提醒", UI.toString(txtAlipay), "取消", "确定", new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            api.getPayOrder(ACTION, payment_id, selectWays, trueMoney, "0", "", UI.toString(txtAlipay));
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                }


                break;
        }
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {
        loadingDialog.dismiss();
    }

    @Override
    public void onRequestStart() {
        loadingDialog.show();
    }

    @Override
    public void getGoPaySuccess(GoPayModel item) {

    }

    @Override
    public void getBeeCloudSuccess(BeeCloudModel item, String channel) {

    }

    @Override
    public void getPayWaySuccess(PayWayModel item) {
        payWayList = item.data;
        selectWays = item.data.get(0).payment_class_name;
        payment_id = item.data.get(0).payment_id + "";
    }


    @Override
    public void getPayOrderSuccess(PayOrderModel data) {
        String url = data.data.alipay_money_links;
//        "go_alipay": 1   // 是否直接调整至支付宝：0 - 否，1 - 是
        isGotoPay = true;
        if (TextUtils.isEmpty(data.data.go_alipay)) {
            data.data.go_alipay = "0";
        }
        if (data.data.go_alipay.equals("1")) {
            if (!checkAliPayInstalled(this)) {
                mWebView.loadUrl(data.data.alipay_money_links);
                return;
            }
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(Const.ALIPAY_START + data.data.alipay_money_links + Const.ALIPAY_END);
            intent.setData(content_url);
            startActivity(intent);
        } else if (data.data.go_alipay.equals("0")) {
            mWebView.loadUrl(url);
        }
    }

    private boolean checkAliPayInstalled(Context context) {

        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

    @Override
    public void getRepayDialogSuccess(RepayStatusDialogModel item) {
//        "is_alerts": 1,  //是否需要弹窗：0 - 否，1 - 是
        //订单状态：0 - 待确认、 1 - 失败、 2 - 成功、4 - 无订单
        explainList = item.data.explain;

        if (item.data.order_status == 2) {
            Map<String, String> map = new HashMap<>();
            map.put("type", Const.SendType.UPDATE_REPAY);
            EventBus.getDefault().post(new OnHomeEventMsg(map));
            ToastUtil.makeText(this, "支付成功").show();
            finish();
        } else if (item.data.order_status == 1) {
            ToastUtil.makeText(this, "支付失败").show();
        } else if (item.data.order_status == 4) {
            ToastUtil.makeText(this, "支付失败").show();
        } else if (item.data.order_status == 0) {
            notice_sn = item.data.notice_sn;
            if (item.data.is_alerts == 0) {
            } else if (item.data.is_alerts == 1) {
                Dialog.showConfirmDialog(this, new Dialog.DialogDefaultClickListener() {
                    //                确认支付成功
                    @Override
                    public void confirm() {
                        api.confirmDialog(item.data.notice_id, api.SUCCESS);
                    }

                    //                点击支付失败
                    @Override
                    public void cancel() {
                        api.confirmDialog(item.data.notice_id, api.FAILED);

                    }
                });
            }
        }
    }

    @Override
    public void confirmDialogSuccess(ConfirmDilaogModel item, String confirm) {
        if (confirm.equals(api.FAILED)) {
//            finish();
        } else if (confirm.equals(api.SUCCESS)) {
            gotoShenhe(explainList);
        }
    }

    @Override
    public void getRepayDataSuccess(RepayModel item) {
        if (item == null || item.data == null) {
            return;
        }
        totalData = item.data;
        txtBorrowDate.setText("借款日期\n" + item.getData().repay_start_time);
        txtRepayDate.setText("还款日期\n" + item.getData().repay_end_time);
        txtYuqiFee.setText("逾期费用\n" + item.getData().impose_all_money_format);
        txtTips.setText("还款倒计时(天)");
        if (item.data.impose_day > 0) {
            txtTips.setText("已逾期时长(天)");
            progressYuqi.setVisibility(View.VISIBLE);
            progressYuqi.setText(item.data.impose_day + "");
            progressNormal.setVisibility(View.GONE);
            btnPayMoney.setShapeSolidColor(0xffFF5D5B).setUseShape();
            txtTipsBottom.setVisibility(View.VISIBLE);
            txtBenxi.setText("(本息+逾期费用)");
            layoutTopColor.setVisibility(View.GONE);
            layoutTopColorSec.setVisibility(View.VISIBLE);
            isYuqi = true;

        } else {
            progressNormal.setProgressSec(Float.valueOf(item.data.remaining_days), Float.valueOf(item.data.repay_time_format.replace("天", "")));
            txtTips.setText("还款倒计时(天)");
            progressNormal.setVisibility(View.VISIBLE);
            txtTime.setText(item.data.remaining_days + "");
            btnPayMoney.setShapeSolidColor(0xff4C81FF).setUseShape();

//            layoutTopColor.setShapeGradientStartColor(0xffFE7E6F).setShapeGradientEndColor(0xffFB494F).setShapeGradientOrientation(SuperButton.LEFT_RIGHT).setUseShape();
            progressYuqi.setVisibility(View.GONE);
            txtTipsBottom.setVisibility(View.GONE);

            isYuqi = false;
        }
        txtMoney.setText(item.data.need_repay_money_format.replace("￥", ""));


        if (item.data.renewal_show.equals("0")) {
            layoutXujie.setVisibility(View.GONE);
        } else {
            layoutXujie.setVisibility(View.VISIBLE);
        }
        if (!TextUtils.isEmpty(item.data.renewal_money) && Float.valueOf(item.data.renewal_money) != 0) {
            btnXuqi.setVisibility(View.GONE);
            imgXuqi.setVisibility(View.GONE);
            cbXuqi.setVisibility(View.VISIBLE);
        }

        if (isYuqi) {
            cbAll.setImageResource(R.mipmap.img_pay_check_red);

        } else {
            cbAll.setImageResource(R.mipmap.img_pay_cb_open);
        }
        ACTION = ACTION_REPAY;


        setMoneyData(false);
    }

    @Override
    public void getDealBefore(DealBeforeV3Model item) {
        switch (item.data.step) {
            case 0:
                Dialog.showAlipayAddTips(this, "提醒", UI.toString(txtAlipay), "取消", "确定", new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        api.getPayOrder(ACTION, payment_id, selectWays, trueMoney, "0", "", UI.toString(txtAlipay));
                    }

                    @Override
                    public void cancel() {

                    }
                });
                break;
            case 1:
//                api.getOneKeyIdentity();
                break;
            case 2:
                Dialog.needOtherData(this, new Dialog.DialogClickListener() {
                    @Override
                    public void confirm() {
                        if (item.data.uplists != null && item.data.uplists.size() != 0) {
                            Intent intent = new Intent();
                            switch (item.data.uplists.get(0).remark) {
                                case Const.IdentityType.yunyin:
                                    intent.setClass(V3RepayMoneyActivity.this, V3YunYingIdentityActivity.class);
                                    break;
                                case Const.IdentityType.contacts:
                                    intent.setClass(V3RepayMoneyActivity.this, V3AddressIdentityActivity.class);
                                    break;
                                case Const.IdentityType.realname:
                                    intent.setClass(V3RepayMoneyActivity.this, V3IdcardIdentityActivity.class);
                                    break;
                                case Const.IdentityType.taobao:
                                    intent.setClass(V3RepayMoneyActivity.this, V3TaobaoIdentityActivity.class);
                                    break;
                                case Const.IdentityType.face_detect:
                                    intent.setClass(V3RepayMoneyActivity.this, V3FaceIdentityOneActivity.class);
                                    break;
                                case Const.IdentityType.xuexin:
                                    intent.setClass(V3RepayMoneyActivity.this, V3XueXinIdentityActivity.class);
                                    break;
                            }
                            intent.putExtra(Const.KEY.SOME_IDENTITY_KEY, item.data.uplists);
                            startActivity(intent);
                            overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                        }
                    }
                });

                break;
            case 3:
                Dialog.showDefaultV3Dialog(this, "提示", "您的认证资料正在更新中这可能需要几分钟的时间，请耐心等待", "", "我知道了", new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {

                    }

                    @Override
                    public void cancel() {

                    }
                });
                break;
        }
    }

    private void setMoneyData(boolean isXuqi) {
        if (isXuqi) {
//            如果是续期的话
            if (isYuqi) {
//                如果是逾期的话，有逾期费
                trueMoney = totalData.renewal_money;
                txtBenxi.setText("(续期费+逾期费用)");
            } else {
                trueMoney = totalData.renewal_money;
                txtBenxi.setText("(续期费用)");
            }
        } else {
            //            如果不是续期的话
            if (isYuqi) {
                txtBenxi.setText("(本息+逾期费用)");
            } else {
                txtBenxi.setText("(本息)");
            }
            trueMoney = totalData.month_need_all_repay_money + "";
        }

        txtNeedPay.setText(trueMoney + "元");
        txtMoneyAll.setText(trueMoney + "");


//        if (isYuqi) {
//            if (isXuqi) {
//                trueMoney = xuqiTotal;
//            } else {
//                trueMoney = totalData.month_need_all_repay_money + "";
//            }
////            trueMoney = +Float.valueOf(totalData.impose_all_money_format.replace("￥","").replace(",",""));
//            txtNeedPay.setText(trueMoney + "元");
//            txtMoneyAll.setText(trueMoney + "");
//        } else {
//            if (isXuqi) {
//
//            } else {
//
//            }
//            trueMoney = totalData.month_need_all_repay_money + "";
//            txtNeedPay.setText(trueMoney + "元");
//            txtMoneyAll.setText(trueMoney + "");
//        }

    }

    private void gotoShenhe(ArrayList<String> explain) {
        Intent intent = new Intent(this, ShenHeActivity.class);
//        intent.putExtra("deal_id", dealId);
//        intent.putExtra("money", mMoney + "");
//        intent.putExtra("overdue", overdue);
//        intent.putExtra("total_money", totalMoney);
//        intent.putExtra("balance", balance);
        intent.putExtra("order", notice_sn);
        intent.putStringArrayListExtra("explain", explain);
        startActivity(intent);
        overridePendingTransition(R.anim.right_enter, R.anim.left_out);
        finish();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isGotoPay) {
            isGotoPay = false;
            api.getRepayDialog();
        }
    }

}
